<?php
namespace app\decorate\controller;
use app\AdminRest;
use app\ApiRest;
use think\App;
use think\facade\Db;
use think\Request;
use app\decorate\model\IndexCollect as collect_model;
use app\decorate\model\IndexCase;
use app\decorate\model\IndexSite;
use app\decorate\model\IndexNews;

class IndexCollect extends ApiRest{
    protected $model;
    public function __construct(App $app) {
        parent::__construct($app);
        $this->model = new collect_model();
    }

    /**
     * User: chenniang
     * Date: 2019-10-09 15:58
     * @return \think\Response
     * descption:收藏列表
     */
    public function collectList(){
        $input = $this->_param;
        $dis[] = ['uniacid','=',$this->_uniacid];
        $dis[] = ['user_id','=',$this->getUserId()];
        $dis[] = ['type'   ,'=',$input['type']];
        $data  = $this->model->collectList($dis);
        return $this->success($data);
    }

    /**
     * User: chenniang
     * Date: 2019-10-09 15:58
     * @return \think\Response
     * descption:添加取消收藏
     */
    public function collectUpdate(){
        $input = $this->_input;
        $input['uniacid'] = $this->_uniacid;
        $input['user_id'] = $this->getUserId();
        $dis[] = ['user_id','=',$this->getUserId()];
        $dis[] = ['news_id','=',$input['news_id']];
        $dis[] = ['type','=',$input['type']];
        $model = $this->getModel($input['type']);

        if($input['status']==1){
            $info  = $this->model->collectInfo($dis);
             $model->where(['id'=>$input['news_id']])->update(['collect'=>Db::raw('collect+1')]);
            if(!empty($info)){
                $this->model->collectUpdate($dis,['status'=>1]);
            }else{
                $this->model->collectAdd($input);
            }
        }else{
            $model->where(['id'=>$input['news_id']])->update(['collect'=>Db::raw('collect-1')]);
            $this->model->collectUpdate($dis,['status'=>0]);
        }
        return $this->success(true);
    }


    /**
     * User: chenniang
     * Date: 2019-10-24 11:41
     * @param $type
     * @return IndexCase|IndexNews|IndexSite
     * descption:获取model
     */
    public function getModel($type){
        switch ($type){
            case 1:
                $model = new IndexCase();
                break;
            case 2:
                $model = new IndexSite();
                break;
            case 3:
                $model = new IndexNews();
                break;
        }
        return $model;
    }

}
